<?php

namespace App\Http\Controllers\Notify;

use App\Http\Controllers\BaseController;
use App\Http\Logic\DheOrderLogic;
use App\Http\Logic\MachineLogic;
use App\Http\Logic\OrderLogic;
use App\Http\Logic\PayLogic;
use App\Http\Requests\DheNotifyRequest;
use App\Logic\LogLogic;
use App\Services\DaHuangService;

class DheNotifyController extends BaseController
{
    public function dheResponse($message = "Error", $code = -1, $content = [])
    {
        $res = [
            'isSuccess' => $code == 200 ? true : false,
            'code'      => $code,
            'message'   => $message
        ];

        if(!empty($content)){
            $res['content'] = $content;
        }

        return response()->json($res);
    }

    /**
     * @notes 大黄鹅订单完结回调
     * @param DheNotifyRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     * @author Evil丿
     * @date 2024/06/14 15:32
     */
    public function DheOrderFinish(DheNotifyRequest $request)
    {
        $params = $request -> all();

        $reqId = $params['reqId'];

        $reqData = $params['reqData'];

        LogLogic::setDheLogs($reqId, 'notify', $params);

        if(!DaHuangService::checkSign($params)) {
            return $this->dheResponse('Sign Error', 401);
        }

        $body = DaHuangService::formatAttach($reqData);

        $order_info = OrderLogic::getLastDoingOrder($body['memberNo'], 1, $body['device_code']);
        if($order_info === false) {
            $content = OrderLogic::addSupplementOrder($reqId, $body, 1);

            if($content === false ) {
                return self::dheResponse('Order Not Found', 500);
            } else {
                return self::dheResponse('OK', 200, $content);
            }
        }

        MachineLogic::clearMachineCacheLock($order_info -> order_sn, $order_info -> door_num);

        $content = DheOrderLogic::hasNotifyOrder($reqData['outTradeNo']);

        if($content) {
            return $this->dheResponse('OK', 200, $content);
        }

        $res = DheOrderLogic::setNotifyOrder($order_info -> id, $reqId, $body);

        if(!$res) {
            return $this->dheResponse('Dhe Order Insert Error', 500);
        }

        $amount = $body['totalAmount'];

        $content = [
            'tradeNo'       => $order_info -> order_sn,
            'outTradeNo'    => $body['outTradeNo'],
            'orderStatus'   => 'NO_PAY',
            'totalAmount'   => $amount,
            'memberNo'      => $body['memberNo'],
            'paidTime'      => date('Y-m-d H:i:s', time())
        ];

        $res = PayLogic::goPay($order_info -> toArray(), $amount, $body['goodsInfos']);

        if($res === false) {
            return $this->dheResponse(PayLogic::getErrorMessage());
        }

        return $this->dheResponse('OK', 200, $content);
    }
}
